package cn.codeforfun.initialization.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author wangbin
 */
@Configuration
public class DatasourceConfiguration {
    private static final String DRIVER_CLASS_MYSQL = "com.mysql.cj.jdbc.Driver";
    private static final String DRIVER_CLASS_H2 = "org.h2.Driver";
    @Resource
    private DbConfigurationProperties properties;

    @Bean
    public DataSource dataSource() throws IOException {
        DruidDataSource dataSource = new DruidDataSource();
        String mysql = "mysql";
        if (mysql.equals(properties.getType())) {
            dataSource.setUsername(properties.getUsername());
            String url = "jdbc:mysql://" + properties.getHost() + ":" + properties.getPort() + "/" + properties.getName()
                    + "?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&createDatabaseIfNotExist=true";
            dataSource.setUrl(url);
            dataSource.setDriverClassName(DRIVER_CLASS_MYSQL);
            dataSource.setPassword(properties.getPassword());
        } else {
            Path tempDirectory = Files.createTempDirectory("excel-");
            String tempPath = tempDirectory.toString();
            dataSource.setUsername("sa");
            dataSource.setPassword("sa");
            dataSource.setUrl("jdbc:h2:mem:initialization");
            System.out.println(tempPath);
            dataSource.setDriverClassName(DRIVER_CLASS_H2);
        }
        return dataSource;
    }
}
